package com.mytravel

import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.widget.EditText
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.android.architecture.extension.click
import com.android.architecture.ui.page.BaseActivity
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.mytravel.databinding.ActivityMainBinding


/**
 * Created by SuQi on 2024/9/26.
 * Describe:
 */
class MainActivity : BaseActivity() {

    private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private val HANDLER = Handler(Looper.getMainLooper())

    override fun initView() {
        setContentView(binding.root)
        updateUI()
        binding.llUrl.click {
            showInputUrl()
        }
        binding.llTime.click {
            showInputTime()
        }
        binding.llSn.click {
            showInputSN()
        }
        binding.btUpload.click {
            requestPermission()
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                startForegroundService(Intent(this, UploadService::class.java));
            } else {
                startService(Intent(this, UploadService::class.java))
            }
            ToastUtils.show("触发自动上送成功")
        }
        requestPermission()
    }

    override fun onResume() {
        super.onResume()
        updateUI()
    }

    override fun onPause() {
        super.onPause()
        HANDLER.removeCallbacksAndMessages(null)
    }

    private fun showInputUrl() {
        val editText = EditText(this)
        val builder = AlertDialog.Builder(this).setTitle("输入Url").setView(editText)
            .setPositiveButton(
                "OK"
            ) { _, _ ->
                AppCache.saveUrl(editText.text.toString())
                ToastUtils.show("更新Url成功")
                updateUI()
            }
        builder.create().show()
    }

    private fun showInputTime() {
        val editText = EditText(this)
        val builder = AlertDialog.Builder(this).setTitle("输入间隔时间（分钟）").setView(editText)
            .setPositiveButton(
                "OK"
            ) { _, _ ->
                try {
                    AppCache.saveIntervalTime(editText.text.toString().toInt())
                    ToastUtils.show("更新间隔时间成功")
                    updateUI()
                } catch (e: Exception) {
                    ToastUtils.show("更新间隔时间失败")
                }
            }
        builder.create().show()
    }

    private fun showInputSN() {
        val editText = EditText(this)
        val builder = AlertDialog.Builder(this).setTitle("输入SN").setView(editText)
            .setPositiveButton(
                "OK"
            ) { _, _ ->
                AppCache.saveSn(editText.text.toString())
                ToastUtils.show("更新SN成功")
                updateUI()
            }
        builder.create().show()
    }


    private fun updateUI() {
        binding.tvUrl.text = AppCache.getUrl()
        binding.tvTime.text = AppCache.getIntervalTime().toString()
        binding.tvSn.text = AppCache.getSn()
        binding.tvUploadTimes.text = AppCache.getUploadTimes().toString()

        HANDLER.removeCallbacksAndMessages(null)
        HANDLER.postDelayed({
            updateUI()
        }, 200)
    }

    private fun requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (ContextCompat.checkSelfPermission(this, Permission.ACCESS_BACKGROUND_LOCATION)
                != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Permission.ACCESS_BACKGROUND_LOCATION),
                    10
                )
            }
        }

        XXPermissions.with(this)
            .permission(
                Permission.ACCESS_FINE_LOCATION,
                Permission.ACCESS_COARSE_LOCATION,
                Permission.READ_PHONE_STATE,
                Permission.POST_NOTIFICATIONS,

                )
            .request(object : OnPermissionCallback {
                override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                }
            })
    }

    override fun onDestroy() {
        HANDLER.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

}